package com.sxkj.common.wechat;

import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.response.BaseResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.github.sd4324530.fastweixin.util.BeanUtil;
import com.github.sd4324530.fastweixin.util.JSONUtil;
import org.apache.commons.lang3.StringUtils;

public class MyOauthAPI extends OauthAPI {

	public MyOauthAPI(ApiConfig config) {
		super(config);
	}
	/**
     * 用户同意授权后在回调url中会得到code，调用此方法用code换token以及openid，所以如果仅仅是授权openid，到这步就结束了
     *
     * @param code 授权后得到的code
     * @return token对象
     */
    public OauthGetTokenResponse getToken(String code) {
    	//判断access_token有效时长 有效的则直接返回
        BeanUtil.requireNonNull(code, "code is null");
        String url = BASE_API_URL + "sns/oauth2/access_token?appid=" + this.config.getAppid() + "&secret=" + this.config.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        BaseResponse r = executeGet(url);
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        OauthGetTokenResponse response = JSONUtil.toBean(resultJson, OauthGetTokenResponse.class);
        if(StringUtils.isBlank(response.getAccessToken())) {
        	JSONObject jo= JSONObject.parseObject(resultJson);
        	String key="access_token";
        	if(jo.containsKey(key)) {
        		response.setAccessToken(jo.getString(key));
        	}
        }
        return response;
    }
	/**
     * 获取用户详细信息
     *
     * @param token  token
     * @param openid 用户openid
     * @return 用户信息对象
     */
    public GetUserInfoResponse getUserInfo(String token, String openid) {
        BeanUtil.requireNonNull(token, "token is null");
        BeanUtil.requireNonNull(openid, "openid is null");
        String url = BASE_API_URL + "sns/userinfo?access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
        BaseResponse r = executeGet(url);
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        return JSONUtil.toBean(resultJson, GetUserInfoResponse.class);
    }
}
